<template>
  <div>
    <div class="margin-container-list">
      <el-tabs v-model="selectStatus" @tab-click="selectStatusClick">
        <el-tab-pane label="已选商品" name="1"></el-tab-pane>
        <el-tab-pane label="未选商品" name="0"></el-tab-pane>
      </el-tabs>
      <!--顶部搜索 -->
      <div class="top-operate-default">
        <div class="search-title">
          <el-select class="select-class" v-model="textCol" style="width: 120px">
            <el-option label="商品名称" value="title"></el-option>
            <el-option label="商品货号" value="goodsCode"></el-option>
          </el-select>
          <el-input @keyup.enter.native="handleSearch" v-model="searchKeyword" placeholder="请输入关键词"
            style="width: 200px"></el-input>
          <el-cascader v-model="categoryIds" placeholder="选择商品零售分类" :props="{ checkStrictly: true }" change-on-select
            :options="categoryData" class="default-input" filterable clearable style="width: 250px"></el-cascader>
          <el-select v-model="queryParams.goodsStatus" v-if="goodsTagObj.goodsTagBusType === 1" placeholder="选择上下架状态"
            clearable style="width: 150px">
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
          <el-select v-model="queryParams.wholesaleGoodsStatus" v-if="goodsTagObj.goodsTagBusType === 2"
            placeholder="选择上下架状态" clearable style="width: 150px">
            <el-option label="上架" value="1"></el-option>
            <el-option label="下架" value="0"></el-option>
          </el-select>
          <!--          <el-select v-model="queryParams.goodsType" placeholder="选择商品类型" clearable style="width: 150px">
            <el-option label="零售商品" value="30"></el-option>
            <el-option label="批发商品" value="31"></el-option>
            <el-option label="零售+批发商品" value="32"></el-option>
          </el-select> -->
          <el-button type="primary" @click="handleSearch" style="margin-left: 15px;">查询</el-button>
          <el-button plain @click="resetSearch">重置</el-button>
        </div>
      </div>
      <div class="btn-search">
        <el-button v-if="selectStatus == 0" @click="handleBatchSelect" type="primary">批量添加</el-button>
        <el-button v-if="selectStatus == 1" @click="handleBatchRemove" type="primary">批量移除</el-button>
      </div>
      <!-- 内容列表 -->
      <div class="table-container">
        <el-table ref="multipleTable" :data="goodsList" v-loading="listLoading"
          @selection-change="handleSelectionChange" element-loading-text="加载中" style="width: 100%">
          <el-table-column width="50px" type="selection"></el-table-column>
          <el-table-column min-width="320px" label="商品名称" prop="title">
            <template slot-scope="scope">
              <div class="flex v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="user-avatar"></label>
                <div class="font-14 pad-l-10">
                  <div>{{scope.row.title}}</div>
                  <div>
                    <span class="font-gray">商品货号：{{scope.row.goodsCode}}</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="100px" label="上下架状态" prop="goodsStatus">
            <template slot-scope="scope">
              <span v-if="goodsTagObj.goodsTagBusType === 1">
                <span>{{dict.goodsStatus[scope.row.goodsStatus]}}</span>
              </span>
              <span v-else-if="goodsTagObj.goodsTagBusType === 2">
                <span>{{dict.goodsStatus[scope.row.wholesaleGoodsStatus]}}</span>
              </span>
              <!--              <span v-else-if="scope.row.goodsType === 32">
                <span>{{dict.goodsStatus[scope.row.wholesaleGoodsStatus || scope.row.goodsStatus]}}</span>
              </span> -->
            </template>
          </el-table-column>
          <el-table-column width="120px" label="零售价格(元)" prop="sellPrice"></el-table-column>
          <el-table-column width="100px" label="库存" prop="stock">
            <template slot-scope="scope">
              {{scope.row.stock || 0}}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="商品类型" prop="goodsType">
            <template slot-scope="scope">
              {{dict.goodsType[scope.row.goodsType]}}
            </template>
          </el-table-column>
          <el-table-column width="150px" label="操作">
            <template slot-scope="scope">
              <el-button v-if="selectStatus == 1" type="primary" @click="removeGoodsId(scope.row.goodsId)">移除
              </el-button>
              <el-button v-if="selectStatus == 0" type="primary" @click="addGoodsId(scope.row.goodsId)">添加</el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination :total="total" :page.sync="queryParams.currentPage" :limit.sync="queryParams.size"
          @pagination="initGoodsList" />
      </div>
    </div>
  </div>
</template>

<script>
  import {
    listGoodsCategory,
    listWholesaleGoodsCategory
  } from '@/api/goods/goods'
  import {
    pageGoodsTagSelectGoods,
    saveGoodsTagDetail
  } from '@/api/goods/goodsTag'
  import {
    getDictByGroupName
  } from '@/api/common/common'
  export default {
    props: {
      goodsTagId: {
        type: Number,
        default: 0
      },
      // 商品标签对象
      goodsTagObj: {
        type: Object
      }
    },
    data() {
      return {
        queryParams: {
          currentPage: 1,
          size: 10,
          enterpriseId: this.getEnterpriseId()
        },
        total: 0,
        categoryData: [],
        textCol: 'title',
        searchKeyword: '',
        categoryIds: [],
        dict: {
          goodsStatus: {},
          goodsType: {}
        },
        // 选中tab
        selectStatus: '1',
        selectedGoodsIds: [],
        // 勾选商品
        pageSelection: [],
        listLoading: false,
        goodsList: [],
        initGoodsIds: []
      }
    },
    created() {
      if (this.goodsTagObj.goodsList !== null && this.goodsTagObj.goodsList !== undefined) {
        this.goodsTagObj.goodsList.forEach(o => {
          this.initGoodsIds.push(o.goodsId)
          this.selectedGoodsIds.push(o.goodsId)
        })
      }
      this.initDict()
      this.listGoodsCategory()
      this.initGoodsList()
    },
    methods: {
      selectStatusClick() {
        this.resetSearch()
      },
      // 勾选
      handleSelectionChange(items) {
        if (items.length === 0) {
          this.pageSelection[this.queryParams.currentPage] = []
        } else {
          this.pageSelection[this.queryParams.currentPage] = items.map(item => item.goodsId)
        }
      },
      // 初始化数据字典
      initDict() {
        getDictByGroupName('ProjectGoodsDTO').then(response => {
          this.dict = response.data
        })
      },
      // 获取类目
      listGoodsCategory() {
        if (this.selectStatus === '1') {
          listGoodsCategory(this.getEnterpriseId()).then(response => {
            this.categoryData = response.data
          })
        }
        if (this.selectStatus === '2') {
          listWholesaleGoodsCategory(this.getEnterpriseId()).then(response => {
            this.categoryData = response.data
          })
        }
      },
      // 获取商品列表
      initGoodsList() {
        this.listLoading = true
        this.queryParams.title = ''
        this.queryParams.goodsCode = ''
        this.queryParams[this.textCol] = this.searchKeyword
        this.queryParams.selectStatus = this.selectStatus
        this.queryParams.goodsIds = this.selectedGoodsIds.join(',')
        if (this.goodsTagObj.goodsTagBusType === 1) {
          this.queryParams.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
          this.queryParams.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
          this.queryParams.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
          this.queryParams.goodsTypes = '30,32'
        }
        if (this.goodsTagObj.goodsTagBusType === 2) {
          this.queryParams.wholesaleOneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
          this.queryParams.wholesaleTwoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
          this.queryParams.wholesaleThreeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
          this.queryParams.goodsTypes = '31,32'
        }
        pageGoodsTagSelectGoods(this.queryParams).then(response => {
          this.total = response.data.total
          this.goodsList = response.data.records
          this.listLoading = false
        })
      },
      // 查询事件
      handleSearch() {
        this.queryParams.currentPage = 1
        this.initGoodsList()
      },
      // 重置事件
      resetSearch() {
        this.queryParams = {
          enterpriseId: this.getEnterpriseId(),
          currentPage: 1,
          size: 10,
          title: '',
          goodsStatus: '',
          goodsType: ''
        }
        this.textCol = 'title'
        this.searchKeyword = ''
        this.categoryIds = []
        this.initGoodsList()
      },
      // 移除商品
      removeGoodsId(goodsId) {
        this.selectedGoodsIds.splice(this.selectedGoodsIds.findIndex(e => e === goodsId), 1)
        this.initGoodsList()
      },
      // 添加商品
      addGoodsId(goodsId) {
        this.selectedGoodsIds.push(goodsId)
        this.initGoodsList()
      },
      // 批量移除商品
      handleBatchRemove() {
        if (this.pageSelection.length === 0) {
          this.msgError('请勾选商品')
          return
        }
        const goodsIds = this.pageSelection[this.queryParams.currentPage]
        goodsIds.forEach(goodsId => this.selectedGoodsIds.splice(this.selectedGoodsIds.findIndex(e => e === goodsId),
          1))
        this.initGoodsList()
      },
      // 批量选择商品
      handleBatchSelect() {
        if (this.pageSelection.length === 0) {
          this.msgError('请勾选商品')
          return
        }
        const goodsIds = this.pageSelection[this.queryParams.currentPage]
        goodsIds.forEach(goodsId => this.selectedGoodsIds.push(goodsId))
        this.initGoodsList()
      },
      // 保存事件
      saveSelectGoods() {
        if (this.compareOldAndNow()) {
          this.$emit('saveDetail', false)
        } else {
          const form = {
            goodsTagId: this.goodsTagObj.goodsTagId,
            goodsIdList: this.selectedGoodsIds,
            goodsTagBusType: this.goodsTagObj.goodsTagBusType
          }
          saveGoodsTagDetail(form).then(response => {
            if (response.isError) return
            this.$emit('saveDetail', true)
            this.msgSuccess('保存成功!')
          })
        }
      },
      // 比较新旧值
      compareOldAndNow() {
        const old = this.initGoodsIds.join(',')
        const now = this.selectedGoodsIds.join(',')
        return old === now
      }
    }
  }
</script>

<style lang="less" scoped>
  .user-avatar {
    width: 68px;
    height: 68px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }

  .search-title {
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -ms-flex-align: center;
    align-items: center;
    -ms-flex-negative: 0;
    flex-shrink: 0;
    padding: 0 20px;
  }
</style>
